
//初始化设备数据
var deviceListInitUrl = "/operation/api/hkws/userVideo/v1/view"
//添加设备信息
var addDeviceMsgUrl = "/operation/api/hkws/video/v1/add"
// 获取组织机构数据
var getSingleDataUrl = "/operation/api/hkws/userOrg/v1/view"
// 删除设备信息 
var deleteDeviceMsgUrl = "/operation/api/hkws/video/v1/del"
//修改
var modifyDeviceMsgUrl = "/operation/api/hkws/video/v1/edit"
var orgIdGlobal;//门店id
var deviceRow;//当前点击设备信息
var defaultPassWordInputText;//存储用户默认密码框字段
var changeFlag = true;
window.onload = function () {
    // 获取组织机构数据
    getSingleData()
    questionFlowListInit("hkws")
}
// 渲染组织机构数据
function getSingleData() {
    // s
    var columns = [
        { checkbox: true, field: "checkvalue", visible: false },
        { field: 'orgId', title: '组织id', align: "center" },
        { field: 'orgName', title: '门店', align: "center" }
    ]
    $('#storeTable').bootstrapTable({
        method: 'post',
        contentType: 'application/json',
        url: getSingleDataUrl,
        dataField: "data",
        pageNumber: 1,
        escape: true,
        cache: false,
        pagination: true,
        search: true,
        uniqueId: "orgId",
        queryParams: function (params) {
            console.log(params)
            return {
                pageSize: params.limit,
                page: params.offset / params.limit + 1,
                search: params.search,
                userId: localStorage.getItem("userId")
            }
        },
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50],
        responseHandler: function (result) {
            var errcode = result.message;
            var transDateRes = [];
            if (result.data && result.data.length > 0) {
                transDateRes = result.data;
            }
            if (errcode == "成功") {
                return {
                    total: result.data.conf ? result.data.conf.totalNum : 0,
                    data: transDateRes
                };
            } else {
                return;
            }
        },
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        showHeader: true,
        columns: columns,
        onClickRow: function (row, $element) {
            $(".input-group").show()
            orgIdGlobal = row.orgId
            $($element).addClass("changeColor").siblings().removeClass("changeColor")
            questionFlowListInit(row.orgId)
        },
        onDblClickRow: function (row) {

        },
        onClickCell: function (row, $element) {
        },
        onCheck: function (row) {
        }
    });
    // e
}

// 点击删除按钮
$(document).on("click", ".deleteTr", function () {

    if (!deviceRow) {
        layer.msg("请选择删除设备名称");
    } else {
        deleteDeviceMsg(deviceRow.id)
    }
})
// 点击关闭模态框按钮
$(document).on("click", ".closeModel", function () {
    questionFlowListInit(orgIdGlobal)
})
// 点击保存按钮
$(document).on("click", "#sava-edit-btn", function () {
    if (!$(".deviceName").val().trim()) {
        layer.msg("新增设备名称不能为空");
    } else if ($(".deviceName").val().length > 50) {
        layer.msg("新增设备名称长度过长");
    } else if (!$(".userName").val().trim()) {
        layer.msg("用户名不能为空");
    } else if ($(".userName").val().length > 32) {
        layer.msg("用户名称长度过长");
    } else if (!$(".passWord").val().trim()) {
        layer.msg("密码不能为空");
    } else if ($(".passWord").val().length > 20) {
        layer.msg("密码长度过长");
    } else if (!$(".urlPath").val().trim()) {
        layer.msg("地址不能为空");
    } else if ($(".urlPath").val().length > 200) {
        layer.msg("地址长度过长");
    } else if ($(".reMark").val().length > 200) {
        layer.msg("密码长度过长");
    }
    else {
        var params;
        // 判断是否存在deviceRow，有则是修改，否则是新增
        if (!deviceRow) {
            params = {
                "name": $(".deviceName").val(),
                "remark": $(".reMark").val(),
                "orgId": orgIdGlobal,
                "userId": $(".userName").val(),
                "userPass": $(".passWord").val(),
                "url": $(".urlPath").val()
            }
            addDeviceMsg(params)
        } else {//修改  isEditPass为1表示修改密码2表示未修改密码    // checkPassWord()为true    未修改密码
            params = {
                "orgId": deviceRow.orgId,
                "userId": $(".userName").val(),
                "userPass": $(".passWord").val(),
                "name": $(".deviceName").val(),
                "remark": $(".reMark").val(),
                "url": $(".urlPath").val(),
                "id": deviceRow.id,
                "isEditPass": checkPassWord() ? "2" : "1"
            }
            modifyDeviceMsg(params)

        }

    }
})
// 点击修改按钮
$(document).on("click", ".modify", function () {
    if (!deviceRow) {
        layer.msg('请选择设备');
    } else {

        $(".deviceName").val(deviceRow.name)
        $(".reMark").val(deviceRow.remark)
        $(".userName").val(deviceRow.userId)
        // 默认样式
        $(".passWord").addClass("defaultStyle")
        $(".passWord").val("使用默认")
        defaultPassWordInputText = $(".passWord").val()
        $(".urlPath").val(deviceRow.url)
        $("#myModal").modal()
    }
})

// 点击新增按钮add
$(document).on("click", ".add", function () {
    if (!orgIdGlobal) {
        layer.msg('请选择门店');
    } else {
        deviceRow = ""
        $(".passWord").removeClass("defaultStyle")
        $(".deviceName").val("")
        $(".reMark").val("")
        $(".userName").val("")
        $(".passWord").val("")
        $(".urlPath").val("")
        $("#myModal").modal()
    }
})
// 查询设备信息方法方法
function questionFlowListInit(orgId) {
    $("#deviceTable").bootstrapTable('destroy');
    changeFlag = true
    deviceRow = ""
    // s
    var columns = [
        { checkbox: true, field: "checkvalue", visible: false },
        { field: 'id', title: 'id', align: "center", visible: false },
        { field: 'name', title: '设备名称', align: "center" }
    ]
    $('#deviceTable').bootstrapTable({
        method: 'post',
        contentType: 'application/json',
        url: deviceListInitUrl,
        dataField: "data",
        pageNumber: 1,
        escape: true,
        cache: false,
        uniqueId: "orgId",
        queryParams: function (params) {

            return {
                pageSize: params.limit,
                page: params.offset / params.limit + 1,
                orgId: orgId
            }
        },
        responseHandler: function (result) {
            var errcode = result.message;
            var transDateRes = result.data;
            if (errcode == "成功") {
                return {
                    data: transDateRes
                };
            } else {
                return;
            }
        },
        showHeader: true,
        columns: columns,
        onClickRow: function (row, $element) {
            deviceRow = row
            $($element).addClass("changeColor").siblings().removeClass("changeColor")
        },
        onDblClickRow: function (row) {
            console.log("id值")
            console.log(row.id)
            window.external.openCamera(row.id, localStorage.getItem("userId"));
        },
        onCheck: function (row) {
        }


    });
    // e
}
// 新增设备信息方法
function addDeviceMsg(params) {
    $.ajax({
        type: "post",
        url: addDeviceMsgUrl,
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params),
        cache: false,
        success: function (data) {
            if (data.message === "成功") {
                questionFlowListInit(orgIdGlobal)
                $('#myModal').modal('hide')
                layer.msg('添加成功', { time: 1000, icon: 1 });

            } else {
                layer.msg('添加失败，请重新尝试 ', { time: 1000, icon: 1 });

            }

        },
        error: function () {
            layer.msg('请求出错');
        }
    })
}
// 修改设备信息方法
function modifyDeviceMsg(params) {
    $.ajax({
        url: modifyDeviceMsgUrl,
        type: "post",
        cache: false,
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (data) {

            if (data.message === "成功") {
                layer.msg('修改成功', { time: 1000, icon: 1 });
                questionFlowListInit(orgIdGlobal)
                $('#myModal').modal('hide')
            } else {
                layer.msg('修改失败，请重新尝试', { time: 1000, icon: 1 });

            }

        },
        error: function (e) {

            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    })
}
//删除设备信息方法
function deleteDeviceMsg(ids) {
    // var params = {};
    $.ajax({
        url: deleteDeviceMsgUrl,
        type: "post",
        cache: false,
        data: JSON.stringify({ ids: [ids] }),
        contentType: "application/json",
        success: function (data) {
            if (data.message === "成功") {
                layer.msg('删除成功', { time: 1000, icon: 1 });
                questionFlowListInit(orgIdGlobal)
            } else {
                layer.msg('删除失败，请重新尝试 ', { time: 1000, icon: 1 });
            }
        },
        error: function (e) {
            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    })
}

function checkPassWord() {

    if (changeFlag) {
        if (defaultPassWordInputText != $(".passWord").val()) {
            //修改密码
            $(".passWord").removeClass("defaultStyle")
            changeFlag = false
            return false
        } else {

            //未修改密码
            return true
        }
    }


}
